--[[
连接上zk后，发送 ConnectRequest,并获取了响应

解析响应，并存储状态
发送 getchildren请求，并获得响应，解析响应

--]]


local sock = require('socket')
local jute = require('jute2')
local myutils = require('myutils')


-- local host = 'localhost'
local host = '104.236.132.55'
local port = 2181

local _xid = 0
local _status = {
  zxid = 0,               -- Uint8Array[8]
  timeout = 30000,
  sessionId = 0 ,         -- Uint8Array[8]
  sessionPassword = jute.makeBuffer(16)    -- Uint8Array[16]
}

local request = jute.packWithLength( "ConnectRequest", jute.PROTOCOL_VERSION, _status.zxid, _status.timeout, _status.sessionId, _status.sessionPassword)
local conn = assert(sock.connect(host, port))
conn:send(request)

local b1, status, partial = conn:receive(4) -- first 4 byte = package length
local length = jute.unpackInt(b1)
print('length=' .. length)
local b2, status, partial = conn:receive(length)




-- parse response
-- save to _status
local response = jute.unpack("ConnectResponse", b2)
print(type(response))
myutils.printTbl(response)
_status.timeout =  response.timeout
_status.sessionId = response.sessionId
_status.passwd = response.passwd


-- send get children request
print("phase GetChildren2Request")
_xid = _xid + 1
local header = jute.pack("RequestHeader", _xid, jute.OP_CODES.GET_CHILDREN2)
-- myutils.writeFile(header)
local ustr = jute.makeUstring('/bar')
local ustr = jute.makeUstring('/dubbo')
local request2 = jute.packWithHeader("GetChildren2Request", header, ustr, 0)
print("request2 len=" .. #request2)
-- myutils.writeFile(request2)

conn:send(request2)
local b3, status, partial = conn:receive(4) -- first 4 byte = package length
local length = jute.unpackInt(b3)
print('length=' .. length)
local b4, status, partial = conn:receive(length)
myutils.writeFile(b4)


conn:close()




